import {
    View, FlatList, RefreshControl, TouchableOpacity, AsyncStorage,
    TouchableHighlight, Text, StyleSheet, Image, DeviceEventEmitter, Alert
} from 'react-native';
import React, {PureComponent} from 'react';
import Urls, {getRealUrl, postRealUrl} from '../const/Urls'
import LocalImg from '../const/Images'
import moment from 'moment'
import {Modal, Button, WingBlank, WhiteSpace, Toast} from 'antd-mobile-rn';

const prompt = Modal.prompt;

/*
 * 签证单录入
 */
class PageQzdlr extends PureComponent {

    constructor(props) {
        super(props);
        this.state = {
            user: {
                token: '',
                pilotCode: '',
                pilotName: '',
                bmbm: '',
                pilotID: '',
            },
            data: [],
            isLoading: false,
        };
        this.setUser();
    }

    componentDidMount() {
        this.setState({
            data: [],
        });
        this.setUser();
        DeviceEventEmitter.addListener('commit', () => {
            this.onRefresh();
        })
    }

    setUser() {
        AsyncStorage.getItem("user", (error, result) => {
            if (!error) {

                const data = JSON.parse(result);
                if (data) {
                    this.setState({
                        user: {
                            token: data['token'],
                            pilotCode: data['pilotCode'],
                            pilotName: data['pilotName'],
                            bmbm: data['bmbm'],
                            pilotID: data['pilotID']
                        }
                    });
                    this.loadData();
                } else {
                    this.setState({
                        user: {
                            token: '',
                            pilotCode: '',
                            pilotName: '',
                            bmbm: '',
                            pilotID: ''
                        }
                    });
                }
            }
        })
    }

    render() {
        return (
            <View style={{flexDirection: 'column', flex: 1}}>

                <View style={{
                    flexDirection: 'row',
                    flex: 0,
                    height: 60,
                    alignItems: 'center',
                    justifyContent: 'center',
                    backgroundColor: '#0066FF'
                }}>
                    <View style={{flex: 1, padding: 10}}>
                        <TouchableOpacity onPress={() => this.props.navigation.pop()}>
                            <Image source={LocalImg['backImg']} style={{height: 30, width: 30, resizeMode: 'contain'}}/>
                        </TouchableOpacity>
                    </View>
                    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                        <Text style={{fontSize: 20, color: '#ffffff'}}>签证单录入</Text>
                    </View>

                    <View style={{flex: 1, alignItems: 'flex-end', padding: 10}}>

                    </View>
                </View>

                <View style={{height: 1, backgroundColor: '#CCCCCC'}}/>

                <FlatList
                    data={this.state.data}
                    renderItem={(item, index) => this.renderRow(item, index)}
                    keyExtractor={this.keyExtractor}
                    ItemSeparatorComponent={this.separator}
                    ListFooterComponent={() => this.footerView()}
                    onEndReachedThreshold={0.1}
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.isLoading}
                            onRefresh={() => this.onRefresh()}
                        />
                    }/>

            </View>
        )
    }

    keyExtractor = (item, index) => item.idh + "";

    footerView() {
        return (
            <View style={{flexDirection: 'row', justifyContent: 'center', paddingTop: 20, paddingBottom: 30}}>
                <Text>到底了</Text>
            </View>
        )
    }


    onRefresh() {
        this.setState({
            data: [],
        });
        this.loadData();
    }

    loadData() {
        this.setState({
            isLoading: true
        });

        const request = new Map();
        // request.set('nid', 'TZ00012');
        request.set('nid', this.state.user['pilotCode']);

        fetch(getRealUrl(Urls['qzdlrUrl'], request), {
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json"
            },
        })
            .then(response => response.json())
            .then(responseJson => {
                if (responseJson instanceof Array) {
                    this.setState({
                        data: responseJson,
                    });
                }
                this.setState({
                    isLoading: false,
                });

            })
            .catch(error => {
                console.error(error);
                this.setState({
                    isLoading: false
                });
            });

    }

    separator(index) {
        return (
            <View key={index} style={{height: 1, backgroundColor: '#CCCCCC'}}/>
        )
    }


    renderRow({item, index}) {
        let bColor = index % 2 !== 0 ? "#f9f9f9" : "#ffffff";

        let id = item.idh;
        return (
            <TouchableHighlight key={id}
                                style={{backgroundColor: bColor}}
                                onPress={() => this.enterDetail(index, id)}
            >
                <View style={[styles.text, {flex: 1, marginLeft: 10, marginTop: 10, justifyContent: 'center'}]}>

                    <View style={{flex: 1, flexDirection: 'row'}}>
                        <View>
                            <Text>{item.ship_name}</Text>
                        </View>
                        <View style={{flex: 1, marginLeft: 12}}>
                            <Text>{item.ship_owner}</Text>
                        </View>
                    </View>

                    <View style={{flex: 1, flexDirection: 'row'}}>
                        <View style={{flex: 1}}>
                            <Text>始：{item.pilot_place_from}</Text>
                        </View>
                        <View style={{flex: 1}}>
                            <Text>至：{item.pilot_place_to}</Text>
                        </View>
                    </View>
                </View>

            </TouchableHighlight>
        )
    }


    search() {
        this.setState({
            data: [],
        });
        this.loadData();
    }

    enterDetail(index, id) {
        this.props.navigation.navigate('PageQzdlrDetail', {
            id: this.state.user['bmbm'],
            data: this.state.data[index],
            refresh: () => this.onRefresh()
        })
    }


}

const styles = StyleSheet.create({
    phone: {
        flex: 1,
        textDecorationLine: 'underline',
        color: '#0066FF',
    },
    text: {
        flex: 1
    },
    row: {
        flexDirection: 'column',
        justifyContent: 'center',
        padding: 10,
    },
});


export default PageQzdlr;